# -*- coding:utf-8 -*-
# @Time : 21-8-9 下午1:35
# @Author : zdy
# @File :
# desc:

from UI.CompareCurve import Ui_CompareCurve
from Class.VoltSignal import dataBase, VoltSignal
import pyqtgraph as pg
from Class.GraphBase import GraphBase
from importQT import *
import copy
from Class.Devices import *

class UICompareCurve(QDialog, Ui_CompareCurve):
    def __init__(self):
        super(UICompareCurve, self).__init__()
        self.setupUi(self)
        self.setWindowTitle('比较曲线')
        self.applyResource()
        self.items = [[] for i in range(0, dataBase.maxChannel)]
        self.inittwData()
        self.initGraph()
        self.rbtn0.setText(E1)
        self.rbtn1.setText(E2)
        self.rbtn2.setText(E3)
        self.rbtn3.setText(E4)
        self.rbtn0.toggled.connect(self.switchChannel)
        self.rbtn1.toggled.connect(self.switchChannel)
        self.rbtn2.toggled.connect(self.switchChannel)
        self.rbtn3.toggled.connect(self.switchChannel)
        self.currentChannel = 0
        self.rbtn0.setChecked(1)

        self.btnDelete.clicked.connect(self.btnDelete_clicked)
        self.btnRefresh.clicked.connect(self.btnRefresh_clicked)
        self.cbcurveset.addItems(["释放曲线", "+积分延迟", "原始曲线"])
        self.cbcurveset.setCurrentIndex(0)
        self.cbcurveset.currentIndexChanged.connect(self.cbcurveset_currentIndexChanged)
        # self.splitter.setSizes([1000, 1000])    #以像素为单位指定宽度，超出时，按比例
        self.setAcceptDrops(True)

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def cbcurveset_currentIndexChanged(self):
        self.refreshGraph()

    def btnRefresh_clicked(self):
        self.refreshGraph()

    def switchChannel(self, isChecked):
        if isChecked:
            if self.sender() == self.rbtn0:
                self.currentChannel = 0
            if self.sender() == self.rbtn1:
                self.currentChannel = 1
            if self.sender() == self.rbtn2:
                self.currentChannel = 2
            if self.sender() == self.rbtn3:
                self.currentChannel = 3
            self.refreshGraph()

    def refreshGraph(self):
        """根据表格绘制曲线"""
        for i in self.curve:
            i.clear()
            self.graph.removeItem(i)
        self.curve.clear()
        rowcount = self.twData.rowCount()
        if rowcount > 0:
            for i in range(rowcount):
                if self.twData.item(i, 0).checkState() == Qt.Checked:  # 获取数据、获取颜色、绘制曲线
                    vs = VoltSignal.loadAll(self.twData.item(i, 2).text())
                    if vs is not None:
                        color = self.twData.cellWidget(i, 1).palette().color(QPalette.Background)
                        ydata = []
                        xdata = []
                        if self.cbcurveset.currentIndex() == 0:
                            ydata = vs.listData[self.currentChannel]
                        if self.cbcurveset.currentIndex() == 1: #显示积分延迟部分
                            ydata = vs.getlistDataDelay(self.currentChannel)
                        if self.cbcurveset.currentIndex() == 2: #原始信号
                            ydata = vs.getlistDataInitial(self.currentChannel)
                        xdata = copy.copy(vs.listT)  # 浅拷贝
                        datalen =  len(ydata)
                        while datalen< len(xdata):
                            xdata.pop(len(xdata)-1)
                        self.curve.append(self.graph.plot(x=xdata, y=ydata, pen=pg.mkPen(color=color, width=2)))
        pass

    # region 曲线
    def initGraph(self):
        self.graphBase = GraphBase(self)
        self.graph = self.graphBase.graphwiget
        self.graph.setLabel("left", "U/v")
        self.graph.setLabel("bottom", "T/s")
        self.horizontalLayout.insertWidget(0, self.graph)
        self.curve = []
    # endregion

    def inittwData(self):
        self.twData.setColumnCount(5)
        # 设置表头粗体
        self.twData.setHorizontalHeaderLabels(['包含', "颜色", '日期', '样品名称', '编号'])
        font = self.twData.horizontalHeader().font()
        font.setBold(True)
        self.twData.horizontalHeader().setFont(font)
        self.twData.setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选中的方式
        self.twData.horizontalHeader().setStretchLastSection(True)  # 最后一列填充
        self.twData.setColumnWidth(0, 30)
        self.twData.setColumnWidth(1, 30)
        self.twData.setColumnWidth(2, 150)
        self.twData.verticalHeader().setVisible(False)  # 行首不可见
        self.twData.horizontalHeader().setSectionsClickable(False)  # 表头不可点击

    def setDatas(self, rowIndexs):
        """根据指定rowIndexs，加载数据"""
        for rowSelect in rowIndexs:
            row = self.twData.rowCount()
            self.twData.insertRow(row)
            try:
                item3 = QTableWidgetItem()
                item3.setCheckState(Qt.Checked)
                self.twData.setItem(row, 0, item3)
                btn = QPushButton(self.twData)
                btn.setStyleSheet("background-color:" + QColor.colorNames()[row + 7])
                btn.clicked.connect(self.colorChange)
                self.twData.setCellWidget(row, 1, btn)
                alignment = int(Qt.AlignHCenter | Qt.AlignVCenter)
                item = QTableWidgetItem()
                item.setTextAlignment(alignment)
                item.setData(Qt.DisplayRole, device.modelResult.item(rowSelect, dataBase.dbColId[1]).text())
                self.twData.setItem(row, 2, item)
                item1 = QTableWidgetItem()
                item1.setTextAlignment(alignment)
                item1.setData(Qt.DisplayRole, device.modelResult.item(rowSelect, dataBase.dbColSampleName[1]).text())
                self.twData.setItem(row, 3, item1)
                item2 = QTableWidgetItem()
                item2.setTextAlignment(alignment)
                item2.setData(Qt.DisplayRole,
                              int(device.modelResult.item(rowSelect, dataBase.dbColSampleNum[1]).text()))
                self.twData.setItem(row, 4, item2)
            except:
                print("数据格式错误")
        self.twData.setShowGrid(True)  # 有数据时才起作用

    def colorChange(self):
        # 弹出颜色选择对话框, 返回值是QColor
        # col = QColorDialog.getColor(QColorDialog.currentColor(), self, "修改颜色")
        col = QColorDialog.getColor()
        # 检测用的选择是否合法(点击cancel就是非法,否则就是合法)
        if col.isValid():
            # 同前面一样,设置frame框架的颜色
            self.sender().setStyleSheet(
                'QWidget {background-color: %s}'
                % col.name())

    def btnDelete_clicked(self):
        ranges = self.twData.selectedRanges()
        count = len(ranges)
        row = []
        for i in range(0, count):
            for j in range(ranges[i].topRow(), ranges[i].bottomRow() + 1):
                row.append(j)
        row.sort(key=int, reverse=True)  # 因为删除一行后，后面的行号都会变化，所以用sort方法将list进行降序排列
        for i in row:
            self.twData.removeRow(i)

    def dropEvent(self, a0: QDropEvent) -> None:
        """当拖拽操作在目标控件上被释放时，触发"""
        if a0.mimeData().hasText():
            dropstr = a0.mimeData().text()
            # print(dropstr)
            rowindexsstr = dropstr.split("&")
            rowIndexs = []
            for i in rowindexsstr:
                rowIndexs.append(int(i))
            # print(rowIndexs)
            self.setDatas(rowIndexs)
        pass

    def dragEnterEvent(self, a0: QDragEnterEvent) -> None:
        """拖拽操作时，进入该控件时，触发该事件，"""
        if a0.mimeData().hasText():
            a0.setAccepted(True)
            # print("准备接收drag")
        else:
            a0.setAccepted(False)
            # print("drag不匹配")
        pass
